package ricardotavares.util.hibernate.configuracao;

/*
 * ConfiguracaoRede.java
 *
 * Created on 30/04/2011, 19:21:47
 */

import javax.swing.JOptionPane;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import ricardotavares.util.arquivo.*;

/**
 *
 * @author Ricardo
 */
public class ConfigurationHibernate extends javax.swing.JDialog {

    /*
     * Variaveis de conexão com o banco de dados
     */
    private String host,userName,password,port,dataBase,url,dialect, driver;
    private Configuration configuracao;
    private SessionFactory sessions;
    private Session sessao;
    private Arquivos arquivos = new Arquivos();
    private ricardotavares.util.arquivo.JavaInfo  javaInfo;
    private boolean salvar;

    public ConfigurationHibernate(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        javaInfo = arquivos.read();
        setFormulario();
    }

    /**
     * Preenche o formulário com as informações lidas do JavaInfo.
     *
     * @author            Ricardo Tavares
     */
    private void setFormulario()
    {
        if ((javaInfo != null) && javaInfo.isSalvar()) {
            campoDatabase.setText(javaInfo.getDataBase());
            campoHost.setText(javaInfo.getHost());
            campoPassword.setText(javaInfo.getPassword());
            campoUserName.setText(javaInfo.getUserName());
            campoPort.setText(javaInfo.getPort());
            campoSalvar.setSelected(javaInfo.isSalvar());
        }
    }

    /**
     * Set as informações dos campos nas variáveis.
     *
     * @author            Ricardo Tavares
     */
    private void setParametros()
    {
        host = campoHost.getText();
        userName = campoUserName.getText();
        password = campoPassword.getText();
        port = campoPort.getText();
        dataBase = campoDatabase.getText();
        salvar = campoSalvar.isSelected();
        url = "jdbc:mysql://"+host+":"+port+"/"+dataBase;
        dialect = "org.hibernate.dialect.MySQLDialect";
        driver = "com.mysql.jdbc.Driver";
    }

    /**
     * Configura a classe Configuration com os dados informados na tela.
     *
     * @author            Ricardo Tavares
     */
    private void configuraConexao()
    {
        try{
        setParametros();
        configuracao = new Configuration()
        .setProperty("hibernate.dialect", dialect)
        .setProperty("hibernate.connection.driver_class", driver)
        .setProperty("hibernate.connection.url", url)
        .setProperty("hibernate.connection.username", userName)
        .setProperty("hibernate.connection.password", password);
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, "Ops! erro na configuração.\n"+e,"Configurador do Hibernate",JOptionPane.ERROR_MESSAGE);
        }
    }

     /**
     * Realiza uma tentativa de conexão e caso ocorrá como esperado mostra uma tela de conectado com sucesso.
     *
     * @author            Ricardo Tavares
     */
    private void testarConexao()
    {
        try{
        sessions = configuracao.buildSessionFactory();
        sessao = sessions.openSession(); // open a new Session
        sessao.beginTransaction();
        sessao.getTransaction().commit();
        sessao.close();
        JOptionPane.showMessageDialog(null,"Conectado com Sucesso!");
        }catch(Exception e){
            JOptionPane.showMessageDialog(null,"Opa! erro na conexao.\n"+e,"Configurador do Hibernate",JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * Salvar as informações da tela no computador
     *
     * @author            Ricardo Tavares
     */
    private void save()
    {
        setParametros();
        javaInfo = new JavaInfo(host, dataBase, userName, password, port, salvar);
        arquivos.write(javaInfo);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        campoDatabase = new javax.swing.JTextField();
        jLabel17 = new javax.swing.JLabel();
        jLabel18 = new javax.swing.JLabel();
        jLabel19 = new javax.swing.JLabel();
        jLabel20 = new javax.swing.JLabel();
        campoHost = new javax.swing.JTextField();
        campoUserName = new javax.swing.JTextField();
        campoPort = new javax.swing.JTextField();
        jLabel21 = new javax.swing.JLabel();
        campoSalvar = new javax.swing.JCheckBox();
        jSeparator1 = new javax.swing.JSeparator();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        campoPassword = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(null);

        campoDatabase.setFont(new java.awt.Font("Tahoma", 0, 14));
        getContentPane().add(campoDatabase);
        campoDatabase.setBounds(110, 140, 270, 20);

        jLabel17.setFont(new java.awt.Font("Tahoma", 0, 16));
        jLabel17.setText("Database:");
        getContentPane().add(jLabel17);
        jLabel17.setBounds(20, 140, 110, 20);

        jLabel18.setFont(new java.awt.Font("Tahoma", 0, 16));
        jLabel18.setText("Host:");
        getContentPane().add(jLabel18);
        jLabel18.setBounds(20, 20, 110, 20);

        jLabel19.setFont(new java.awt.Font("Tahoma", 0, 16));
        jLabel19.setText("Username:");
        getContentPane().add(jLabel19);
        jLabel19.setBounds(20, 50, 110, 20);

        jLabel20.setFont(new java.awt.Font("Tahoma", 0, 16));
        jLabel20.setText("Password:");
        getContentPane().add(jLabel20);
        jLabel20.setBounds(20, 80, 110, 20);

        campoHost.setFont(new java.awt.Font("Tahoma", 0, 14));
        getContentPane().add(campoHost);
        campoHost.setBounds(110, 20, 270, 20);

        campoUserName.setFont(new java.awt.Font("Tahoma", 0, 14));
        getContentPane().add(campoUserName);
        campoUserName.setBounds(110, 50, 270, 20);

        campoPort.setFont(new java.awt.Font("Tahoma", 0, 14));
        getContentPane().add(campoPort);
        campoPort.setBounds(110, 110, 270, 20);

        jLabel21.setFont(new java.awt.Font("Tahoma", 0, 16));
        jLabel21.setText("Port:");
        getContentPane().add(jLabel21);
        jLabel21.setBounds(20, 110, 110, 20);

        campoSalvar.setText("Salvar");
        getContentPane().add(campoSalvar);
        campoSalvar.setBounds(300, 80, 81, 23);
        getContentPane().add(jSeparator1);
        jSeparator1.setBounds(0, 220, 410, 10);

        jButton1.setText("Testar Conexão");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1);
        jButton1.setBounds(250, 230, 130, 23);

        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2);
        jButton2.setBounds(150, 230, 90, 23);

        jButton3.setText("Conectar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton3);
        jButton3.setBounds(50, 230, 90, 23);

        campoPassword.setFont(new java.awt.Font("Tahoma", 0, 14));
        getContentPane().add(campoPassword);
        campoPassword.setBounds(110, 80, 180, 23);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-416)/2, (screenSize.height-305)/2, 416, 305);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    configuraConexao();
    testarConexao();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    save();
    dispose();
    }//GEN-LAST:event_jButton3ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                ConfigurationHibernate dialog = new ConfigurationHibernate(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField campoDatabase;
    private javax.swing.JTextField campoHost;
    private javax.swing.JPasswordField campoPassword;
    private javax.swing.JTextField campoPort;
    private javax.swing.JCheckBox campoSalvar;
    private javax.swing.JTextField campoUserName;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JSeparator jSeparator1;
    // End of variables declaration//GEN-END:variables

}
